<?php

require_once(WSB_MODULES_PATH . 'sherpa/models/CouponGateway.php');

class Sherpa_Validator_Coupon extends Zend_Validate_Abstract
{

	const EMPTY_SUBTOTAL = 'sherpaValidatorCouponEmptySubtotal';
	const INVALID_CODE = 'sherpaValidatorCouponInvalidCode';
	const NO_VALUE_LEFT = 'sherpaValidatorCouponNoValueLeft';
	const NOT_YET_ACTIVE = 'sherpaValidatorCouponNotYetActive';
	const NOT_ACTIVE_ANYMORE = 'sherpaValidatorCouponNotActiveAnymore';
	const ORDER_VALUE_TOO_SMALL = 'sherpaValidatorCouponOrderValueTooSmall';

	/**
	 * @var array
	 */
    protected $_messageTemplates = array(
        self::EMPTY_SUBTOTAL => 'Subtotal ist leer',
        self::INVALID_CODE => 'Ungültiger Gutschein-Code.',
        self::NO_VALUE_LEFT => 'Gutschein wurde bereits vollständig eingelöst.',
		self::NOT_YET_ACTIVE => "Gutschein erst ab %value% gültig.",
		self::NOT_ACTIVE_ANYMORE => "Gutschein am %value% abgelaufen.",
		self::ORDER_VALUE_TOO_SMALL => "Gutschein ist erst bei Einkäufen ab CHF %value% gültig.",
    );

    /**
     * @param string $value
     * @param array $context
     * @return boolean
     */
    public function isValid($value, $context = null)
    {
        $this->_setValue($value);
    	$gateway = new Sherpa_Model_CouponGateway();
    	$coupon = $gateway->fetchCoupon($value);

		// Invalid Coupon code
    	if($coupon->isEmpty()) {
    		$this->_error(self::INVALID_CODE);
            return false;
    	}

		// No value left
    	if($coupon->getValueRemaining() <= 0) {
			$this->_error(self::NO_VALUE_LEFT);
            return false;
    	}

		// Not yet active
		if($coupon->getValidFrom() != null && time() < $coupon->getValidFrom(true)) {
        	$this->_setValue(date('d.m.Y', $coupon->getValidFrom(true)));
			$this->_error(self::NOT_YET_ACTIVE);
			return false;
		}

		// Not active anymore
		if($coupon->getValidTo() != null && time() > strtotime('+1 day', $coupon->getValidTo(true))) {
        	$this->_setValue(date('d.m.Y', $coupon->getValidTo(true)));
			$this->_error(self::NOT_ACTIVE_ANYMORE);
			return false;
		}

    	// Subtotal is empty
    	if(empty($context['subtotal'])) {
    		$this->_error(self::EMPTY_SUBTOTAL);
            return false;
    	}

		// Order value to small
		$minOrderValue = $coupon->getMinOrderValue();
		$orderValue = $context['subtotal'];
		if($minOrderValue > 0 && $orderValue < $minOrderValue) {
			$this->_setValue($coupon->getFormattedMinOrderValue(true));
			$this->_error(self::ORDER_VALUE_TOO_SMALL);
			return false;
		}

    	return true;
    }

}
